//
//  DrawingView.m
//  制作画板
//
//  Created by 伍银荣 on 2021/7/13.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "DrawingView.h"
#import "WYRBezierPath.h"

@interface DrawingView ()


@property (nonatomic, strong) NSMutableArray *paths;  //保存线宽的数组



@end

@implementation DrawingView

-(NSMutableArray *)paths {
    if (!_paths) {
        _paths = [NSMutableArray array];
    }
    return _paths;
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code

    //只要渲染和设置颜色在drawRect方法里面就可以了
    
    //遍历数组,渲染每条线
    for (WYRBezierPath *path in self.paths) {
        //设置连接处样式
        [path setLineJoinStyle:kCGLineJoinRound];
        //设置头尾处样式
        [path setLineCapStyle:kCGLineCapRound];
        [path.WyrLineColor set];
        //渲染
        [path stroke];
    }
}

//手指开始在view上移动的时候
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesBegan");
    //获取触摸对象
    UITouch *t = touches.anyObject;
    //获取当前手指的位置
    CGPoint currentPoint = [t locationInView:t.view];
    //创建路径
    WYRBezierPath *path = [WYRBezierPath bezierPath];
    
    //从起点开始画线的时候就设置线宽
    [path setLineWidth:self.lineWidthValue];
    //设置颜色
    [path setWyrLineColor:self.lineColor];
    //重绘
   // [self setNeedsDisplay];
    //从手指在view上的时候就开始画线,起点
    [path moveToPoint:currentPoint];
    //将路径添加到数组中
    [self.paths addObject:path];
}

//手指在view上移动的时候
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesMoved");
    //获取触摸对象
    UITouch *t = touches.anyObject;
    //获取当前手指的位置
    CGPoint currentPoint = [t locationInView:t.view];
    //画线到当前手指的位置
    [self.paths.lastObject addLineToPoint:currentPoint];
    [self setNeedsDisplay];
}

//清屏
- (void)clear {
    [self.paths removeAllObjects];
    [self setNeedsDisplay];
}

//回退
- (void)goBack {
    [self.paths removeLastObject];
    //重绘
    [self setNeedsDisplay];
}

//橡皮
- (void)eraser {
    self.lineColor = self.backgroundColor;
}


@end
